using Microsoft.AspNetCore.Components;
using AntDesign.ProLayout;
using oms.Shared.Data;
using oms.Shared.Services.Redis;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Options;
using StackExchange.Redis;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddAntDesign();
builder.Services.AddScoped(sp => new HttpClient
{
    BaseAddress = new Uri(sp.GetService<NavigationManager>()!.BaseUri)
});
builder.Services.Configure<ProSettings>(builder.Configuration.GetSection("ProSettings"));

// 注册 HttpContextAccessor
builder.Services.AddHttpContextAccessor();

// 绑定 Redis 配置
builder.Services.Configure<RedisConfig>(builder.Configuration.GetSection("RedisSettings"));
builder.Services.AddSingleton<IConnectionMultiplexer>(options =>
{
    var redisConfig = options.GetService<IOptions<RedisConfig>>()?.Value;
    if (string.IsNullOrEmpty(redisConfig?.ConnectionString))
    {
        throw new ArgumentNullException(nameof(redisConfig.ConnectionString), "Redis 连接字符串未配置");
    }

    var configOptions = ConfigurationOptions.Parse(redisConfig.ConnectionString);
    configOptions.ConnectTimeout = redisConfig.ConnectTimeout;
    configOptions.SyncTimeout = redisConfig.SyncTimeout;
    configOptions.DefaultDatabase = redisConfig.Database;
    return ConnectionMultiplexer.Connect(configOptions);
});

// 注册封装的 Redis 服务
builder.Services.AddScoped<IRedisService, RedisService>();

// 数据库上下文
builder.Services.AddDbContext<AppDbContext>(options =>
{
    var connectionString = builder.Configuration.GetConnectionString("MySqlConnection");
    var mysqlVersion = builder.Configuration.GetSection("MySqlVersion").Value;

    options.UseMySql(connectionString,
        string.IsNullOrEmpty(mysqlVersion)
            ? ServerVersion.AutoDetect(connectionString)
            : new MySqlServerVersion(mysqlVersion));

    options.LogTo(
            Console.WriteLine,
            (eventId, logLevel) =>
                logLevel == LogLevel.Information &&
                eventId == RelationalEventId.CommandExecuted
        )
        .EnableSensitiveDataLogging()
        .EnableDetailedErrors()
        ;
});

// 注册数据库 Id 生成器
builder.Services.AddScoped<IdGenerator>();

// 注册实体保存拦截器
builder.Services.AddScoped<EntitySaveInterceptor>();

var app = builder.Build();

// 配置 DbContext 拦截器
using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    // 获取拦截器实例
    var entityInterceptor = services.GetRequiredService<EntitySaveInterceptor>();

    // 获取 DbContext 实例
    var dbContext = services.GetRequiredService<AppDbContext>();

    // 关键修正：通过 DbContext 的内部配置创建 OptionsBuilder
    var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
    // 复制现有配置（如连接字符串、数据库提供器等）
    dbContext.ConfigureOptionsBuilder(optionsBuilder);

    // 添加拦截器
    optionsBuilder.AddInterceptors(entityInterceptor);
}

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();